package coml.jiyun.hp.reviewtopic.net;


import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.support.constraint.Constraints.TAG;

public class HttpUtil {
    private volatile static HttpUtil httpUtil;
    private Retrofit.Builder builder;

    private HttpUtil() {
        //ok
        OkHttpClient okHttpClient=initOkHhttp();
        initRetrifit(okHttpClient);
    }

    private void initRetrifit(OkHttpClient okHttpClient) {
        builder = new Retrofit.Builder()
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create());
    }

    volatile HomeServer homeServer;
    public  HomeServer getHomeServer(){
        if (homeServer==null){
            synchronized (HttpUtil.class){
                if (homeServer==null){
                    homeServer = builder.baseUrl(HomeServer.baseUrl)
                            .build()
                            .create(HomeServer.class);
                }
            }
        }
        return homeServer;
    }

    volatile NaviServer naviServer;
    public NaviServer getNaviServer(){
        if (naviServer == null){
            synchronized (HttpUtil.class){
                naviServer = builder.baseUrl(NaviServer.NaviUrl)
                        .build().create(NaviServer.class);
            }
        }
        return naviServer;
    }


    private OkHttpClient initOkHhttp() {
        OkHttpClient build = new OkHttpClient.Builder()
                .addInterceptor(new Log())
                .build();
        return build;
    }

    public static HttpUtil getInstance(){
        if (httpUtil==null){
            synchronized (HttpUtil.class){
                if (httpUtil==null){
                    httpUtil=new HttpUtil();
                }
            }
        }

        return httpUtil;
    }

    class Log implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            String string = response.peekBody(2048).string();
            android.util.Log.d(TAG, "intercept: "+string);
            return response;
        }
    }
}